<template>
  <div class="bottom-view">
    <div class="flex">
      <n-button
        v-for="item in buttonList"
        :key="item.label"
        type="primary"
        size="large"
        :disabled="item.disabled"
        :loading="item.loading"
        @click="buttonFn(item)"
      >
        {{ $t(`productionCenter.table.${item.label}`) }}
      </n-button>

      <ProSearch
        :choose-item="props.chooseItem"
        @set-pro-search-val-fn="
          (...arg) => {
            emit('setProSearchValFn', ...arg);
          }
        "
      />
    </div>

    <div class="bottom-view-table">
      <div class="bottom-view-table-shift">
        <DFTable
          :columns="tableColumns"
          :row-key="(row: Recordable) => row.id"
          ref="actionRef"
          :pagination="false"
          :max-height="90"
          :size="'small'"
          :noDefaultLoad="true"
          :hasIndex="false"
          :routeName="'productionCenter'"
          :virtual-scroll="true"
          :loading="tableLoading"
          :titleAlign="'center'"
          :align="'center'"
        />
      </div>

      <DFTable
        ref="crossactionRef"
        :columns="crossTableColumns"
        :row-key="(row: Recordable) => row.id"
        :pagination="false"
        size="small"
        :no-default-load="true"
        :has-index="false"
        route-name="productionCenter"
        :loading="tableLoading"
        :is-get-field-info="true"
        :virtual-scroll="true"
        :max-height="400"
        :action-column="tableActionColumn"
        :row-props="rowPropsFn"
        :row-class-name="rowClassNameFn"
        :get-field-info-list="getFieldInfoList"
        :set-field-info-list="setFieldInfoList"
        :titleAlign="'center'"
        :align="'center'"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
  import ProSearch from './ProSearch.vue';
  import { DFTable, DFTableAction } from '@/components/DFTable';
  import { getFieldInfoList, setFieldInfoList } from '@/api/common/index';
  import { emitPrintFn } from '@/utils/print';
  import { t } from '@/i18n';
  import { listMachine } from '@/api/base/machine';
  import { delOrder, updateMachineOrder } from '@/api/production/order';
  import homeSingle from '@/assets/images/homeSingle.png';

  interface Props {
    orderList: any;
    chooseItem: any;
    isAdjuest: any;
    printingTemplateRef: any;
    isAutoChangeOrder: any;
  }

  const props = withDefaults(defineProps<Props>(), {
    orderList: () => [],
    chooseItem: () => null,
    isAdjuest: () => null,
    printingTemplateRef: () => null,
    isAutoChangeOrder: () => null,
  });

  const emit = defineEmits([
    'loadOrderFn',
    'changeChooseItemFn',
    'updateOrderStatusFn',
    'setProSearchValFn',
    'updateAdjuestOrderFn',
    'openPageListDialogFn',
    'openAdjustmentOrderDialogFn',
    'closePageListDialogFn',
    'checkOrderInfoFn',
  ]);

  function rowPropsFn(row) {
    return {
      style: 'cursor: pointer;',
      onClick: () => {
        if (props.chooseItem.orderStatusCode !== '30') emit('changeChooseItemFn', row);
      },
    };
  }

  function rowClassNameFn(row) {
    if (row) {
      const { orderCode = null, orderStatusCode = null } = row;

      if (orderStatusCode === '30' || orderCode === props.chooseItem?.orderCode)
        return 'table-active-color';
    }

    return '';
  }

  const tableLoading = ref(false);

  const buttonList = ref([
    {
      label: 'loadOrder',
      disabled: false,
      loading: false,
    },
    {
      label: 'adjustmentOrder',
      disabled: false,
      loading: false,
    },
    {
      label: 'startWork',
      disabled: false,
      loading: false,
    },
    {
      label: 'adjuestSuccess',
      disabled: false,
      loading: false,
    },
    {
      label: 'stopWork',
      disabled: false,
      loading: false,
    },
    {
      label: 'successWork',
      disabled: false,
      loading: false,
    },
  ]);

  if (props.isAdjuest === '0') {
    const index = buttonList.value.findIndex((item) => item.label === 'adjuestSuccess');

    if (index !== -1) {
      buttonList.value.splice(index, 1);
    }
  }

  const startWorkItem = buttonList.value.find((item) => item.label === 'startWork');

  const adjustmentOrderItem = buttonList.value.find((item) => item.label === 'adjustmentOrder');

  const adjuestSuccessItem = buttonList.value.find((item) => item.label === 'adjuestSuccess');

  const stopWorkItem = buttonList.value.find((item) => item.label === 'stopWork');

  const successWorkItem = buttonList.value.find((item) => item.label === 'successWork');

  async function buttonFn(item) {
    switch (item.label) {
      case 'loadOrder':
        tableLoading.value = true;

        item.loading = true;

        emit('loadOrderFn', () => {
          tableLoading.value = false;

          item.loading = false;
        });

        break;
      case 'adjuestSuccess':
        item.loading = true;

        emit('updateAdjuestOrderFn', () => {
          emit('loadOrderFn', () => {
            item.loading = false;
          });
        });

        break;
      case 'startWork':
      case 'stopWork':
      case 'successWork':
        item.loading = true;

        emit('updateOrderStatusFn', item, () => {
          emit('loadOrderFn', () => {
            item.loading = false;
          });
        });

        break;
      case 'adjustmentOrder':
        emit('openAdjustmentOrderDialogFn');

      default:
        break;
    }
  }

  const crossactionRef = ref(null);

  const actionRef = ref(null);

  const crossTableColumns = ref(
    [
      {
        width: 220,
        widthEn: 220,
        label: 'orderCode',
        render(row) {
          const { orderCode = null, autoFlag } = row;

          const childRender = [h('span', { innerText: orderCode })];

          if (autoFlag === 1) {
            childRender.unshift(h('img', { src: homeSingle }));
          }

          return h(
            'p',
            {
              class: 'table-order-code',
            },
            childRender
          );
        },
      },
      {
        width: 220,
        widthEn: 220,
        label: 'customerOrderNo',
      },
      {
        width: 220,
        widthEn: 220,
        label: 'customerNo',
      },
      {
        width: 220,
        widthEn: 220,
        label: 'erpNo',
      },
      {
        width: 100,
        widthEn: 160,
        label: 'orderStatusName',
      },
      {
        width: 180,
        widthEn: 200,
        label: 'materialCode',
      },
      {
        width: 180,
        widthEn: 200,
        label: 'materialName',
      },
      {
        width: 380,
        widthEn: 420,
        label: 'materialStandards',
      },
      {
        width: 100,
        widthEn: 150,
        label: 'orderNum',
        key: 'orderNum',
        sorter: false,
      },
      {
        width: 100,
        widthEn: 180,
        label: 'paperboardNum',
      },
      {
        width: 380,
        widthEn: 420,
        label: 'paperSize',
      },
      {
        width: 180,
        widthEn: 200,
        label: 'scheduledStartTime',
      },
      {
        width: 180,
        widthEn: 200,
        label: 'scheduledEndTime',
      },
      {
        width: 220,
        widthEn: 220,
        label: 'outModeName',
      },
      {
        width: 100,
        widthEn: 150,
        label: 'adjuestNum',
        key: 'adjuestNum',
        sorter: false,
      },
      {
        width: 220,
        widthEn: 220,
        common: true,
        label: 'remark',
      },
    ].map((item) => ({ ...item, key: item.label, sorter: false }))
  );

  const tableColumns = [
    {
      width: 160,
      label: 'thisShiftTitle',
      key: 'thisShift',
      sorter: false,
    },
    {
      width: 160,
      label: 'orderNum',
      key: 'orderNum',
      sorter: false,
    },
    {
      width: 160,
      label: 'goodProductsNum',
      key: 'goodProductsNum',
      sorter: false,
    },
    {
      width: 160,
      label: 'badNum',
      key: 'badNum',
      sorter: false,
    },
    {
      width: 160,
      label: 'badRate',
      key: 'badRate',
      sorter: false,
    },
    {
      width: 160,
      label: 'toBeProducedNum',
      key: 'toBeProducedNum',
      sorter: false,
    },
    {
      width: 160,
      label: 'adjuestNum',
      key: 'adjuestNum',
      sorter: false,
    },
    {
      width: 160,
      label: 'productionTime',
      key: 'productionTime',
      sorter: false,
    },
    {
      width: 160,
      label: 'shutdownTime',
      key: 'shutdownTime',
      sorter: false,
    },
    {
      width: 160,
      label: 'shutdownNum',
      key: 'shutdownNum',
      sorter: false,
    },
  ];

  const printLoading = ref(false);

  async function handlePrintFn(data) {
    try {
      printLoading.value = true;

      await new Promise((resolve, reject) => {
        emitPrintFn(
          props.printingTemplateRef,
          {
            ...(props.chooseItem || {}),
            ...data,
          },
          (printSuccess) => {
            printLoading.value = false;

            if (!printSuccess) window['$message'].error(t('productionCenter.tips.printError'));
            else window['$message'].success(t('productionCenter.tips.printSuccess'));

            emit('closePageListDialogFn');

            resolve(true);
          },
          (_pRes, printSuccess) => {
            printLoading.value = false;

            if (!printSuccess) window['$message'].error(t('productionCenter.tips.printError'));
            else window['$message'].success(t('productionCenter.tips.printSuccess'));

            reject(false);
          }
        );
      });
    } catch (e) {
      console.log(e);

      printLoading.value = false;
    }
  }

  async function changeMachineFn(data) {
    try {
      await updateMachineOrder(data);

      emit('closePageListDialogFn', true, data.machineCode);
    } catch (e) {
      console.log(e);
    }
  }

  const machineList = ref([]);

  const tableActionColumn = reactive({
    width: 180,
    widthEn: 200,
    label: 'operation',
    key: 'action',
    fixed: 'right',
    common: true,
    render(record) {
      return h(DFTableAction as any, {
        style: 'button',
        actions: [
          {
            label: 'check',
            type: 'primary',
            text: true,
            prop: 'check',
            onClick: () => {
              emit('checkOrderInfoFn', toRaw(record));
            },
          },
          {
            label: 'print',
            type: 'primary',
            text: true,
            prop: 'print',
            onClick: () => {
              let totalStackingNum = '';

              const { orderStatusCode, templateNum, pileNum, producedNum } = record;

              if (orderStatusCode !== '30') {
                const totalNum = Math.ceil((producedNum * (templateNum || 1)) / (pileNum || 1)); // 已生产数 × 模数 ÷ 堆叠数

                totalStackingNum = `${totalNum === 0 ? 1 : totalNum} / ${pileNum || 1}`;
              } else {
                const totalStackingNumDom: any = document.querySelector(
                  '.totalStackingNum .top-view-item-value span'
                );

                if (totalStackingNumDom) {
                  totalStackingNum = totalStackingNumDom?.innerText || '0 / 0';
                }
              }

              emit(
                'openPageListDialogFn',
                {
                  formSchemas: [
                    {
                      label: 'orderNum',
                      required: true,
                      requiredRulesType: 'number',
                      component: 'NInputNumber',
                      componentProps: {
                        maxlength: 50,
                        min: 0,
                        precision: 0,
                        clearable: true,
                        showButton: false,
                      },
                    },
                    {
                      label: 'totalStackingNum',
                    },
                  ],
                  submitDataFn: handlePrintFn,
                },
                t('productionCenter.printTemplate.dialogTitle'),
                { orderNum: record.orderNum, totalStackingNum }
              );
            },
          },
          {
            label: 'changeMachine',
            type: 'error',
            text: true,
            prop: 'changeMachine',
            disabled: record.orderStatusCode === '30',
            onClick: () => {
              emit(
                'openPageListDialogFn',
                {
                  formSchemas: [
                    {
                      label: 'machineName',
                      prop: 'machineCode',
                      component: 'NSelect',
                      options: machineList,
                    },
                  ],
                  submitDataFn: changeMachineFn,
                },
                t('common.button.changeMachine'),
                { machineCode: record.machineCode, id: record.id }
              );
            },
          },
          {
            label: 'delete',
            type: 'error',
            text: true,
            prop: 'delete',
            disabled: record.orderStatusCode === '30',
            onClick: () => {
              const d = window['$dialog'].warning({
                title: t('common.tipMsg.warning'),
                content: t('common.tipMsg.deleteSelectedMsg'),
                positiveText: t('common.tipMsg.sure'),
                negativeText: t('common.tipMsg.cancel'),
                onPositiveClick: async () => {
                  try {
                    d.loading = true;

                    const { message: msg = '' } = await delOrder([record.id]);

                    window['$message'].success(msg || t('common.tipMsg.delSuccess'));

                    emit('loadOrderFn');
                  } catch (e) {
                    console.log(e);
                    d.loading = false;
                  }
                },
                onNegativeClick: () => {},
                onAfterLeave: () => {
                  d.loading = false;
                },
              });
            },
          },
        ],
      });
    },
  });

  function setActionRefTableData(data) {
    actionRef.value?.setTableData(data);
  }

  function setCrossActionRefTableData(data) {
    // console.log(data);
    crossactionRef.value?.setTableData(data);

    // data1.value = data;
  }

  function setTableLoadingFn(val) {
    tableLoading.value = val;
  }

  async function initFn() {
    const res = await listMachine();

    machineList.value =
      res?.data.map((item) => ({ label: item.machineName, value: item.machineCode })) || [];

    // todo
    nextTick(() => {
      setActionRefTableData([{
        id: 0,
        thisShift: t('productionCenter.table.thisShift'),
        orderNum: 0,
        goodProductsNum: 0,
        badNum: 0,
        badRate: 0,
        toBeProducedNum: 0,
        adjuestNum: 0,
        productionTime: 0,
        shutdownTime: 0,
        shutdownNum: 0,
      }]);
    });
  }

  initFn();

  watch(
    props,
    (val) => {
      if (val.chooseItem) {
        const { orderStatusCode, adjuestSuccessTime } = val.chooseItem;

        startWorkItem.disabled = !(orderStatusCode === '20' || orderStatusCode === '60');

        stopWorkItem.disabled = !(orderStatusCode === '30');

        successWorkItem.disabled = !(orderStatusCode === '30');

        if (props.isAdjuest === '1') {
          adjuestSuccessItem.disabled = !(orderStatusCode === '30' && !adjuestSuccessTime);
        }

        adjustmentOrderItem.disabled = false;
      } else {
        startWorkItem.disabled = true;

        if (props.isAdjuest === '1') {
          adjuestSuccessItem.disabled = true;
        } else {
          if (adjuestSuccessItem) {
            adjuestSuccessItem.disabled = true;
          }
        }

        stopWorkItem.disabled = true;

        successWorkItem.disabled = true;

        adjustmentOrderItem.disabled = true;
      }
    },
    { immediate: true, deep: true }
  );

  defineExpose({
    setCrossActionRefTableData,
    setTableLoadingFn,
    setActionRefTableData,
  });
</script>

<style lang="less" scoped>
  .bottom-view {
    background-color: #fff;
    border-radius: 4px;
    margin-top: 16px;

    & > .flex {
      flex-wrap: wrap;
      :deep(.n-button),
      :deep(.searchpro) {
        margin-bottom: 16px;
      }
    }

    .bottom-view-table {
      .bottom-view-table-shift {
        margin-bottom: 16px;
      }

      :deep(.table-active-color) {
        .n-data-table-td {
          background: #ffe8da;
          color: #ff8032 !important;
          font-weight: 600;
        }
      }
    }
  }
</style>

<style lang="less">
  .bottom-view {
    .table-order-code {
      display: flex;
      align-items: center;
      margin: 0;
      padding-left: 20px;
      position: relative;
      img {
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
        width: 16px;
        left: 0;
      }
    }

    .n-data-table-td{
      text-align: center;
    }

    .n-data-table-th__title-wrapper{
      justify-content: center;
    }
  }
</style>
